<template>
  <div class="notification-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h2>通知中心</h2>
          <div class="header-actions">
            <el-button 
              type="primary" 
              @click="markAllAsRead"
              :disabled="unreadCount === 0"
            >
              全部标记为已读
            </el-button>
          </div>
        </div>
      </template>

      <el-table 
        :data="notifications" 
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column width="40">
          <template #default="{ row }">
            <div v-if="!row.isRead" class="unread-indicator"></div>
          </template>
        </el-table-column>
        
        <el-table-column label="通知内容">
          <template #default="{ row }">
            <div :class="['notification-content', { unread: !row.isRead }]">
              <strong>{{ row.title }}</strong>
              <p>{{ row.content }}</p>
              
              <!-- 显示关联物品信息 -->
              <div v-if="row.lostItemName" class="related-item">
                <el-tag type="danger">失物</el-tag> {{ row.lostItemName }}
              </div>
              <div v-else-if="row.foundItemName" class="related-item">
                <el-tag type="success">招领</el-tag> {{ row.foundItemName }}
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.addTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
  <template #default="{ row }">
    <el-button 
      v-if="!row.isRead"
      type="primary" 
      size="small"
      @click.stop="markAsRead(row)"
    >
      标记已读
    </el-button>
    <el-tag 
      v-else
      type="success"
      size="small"
    >
      已读
    </el-tag>
  </template>
</el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          layout="prev, pager, next"
          @current-change="loadNotifications"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const notifications = ref([])
const unreadCount = ref(0)

const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 加载通知数据
const loadNotifications = async () => {
  const token = localStorage.getItem('token')
  if (!token) return
  
  try {
    const response = await axios.get('/notifications', {
      params: {
        pageNum: pagination.value.pageNum,
        pageSize: pagination.value.pageSize
      },
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    
    if (response.data && response.data.data) {
      notifications.value = response.data.data.records || []
      pagination.value.total = response.data.data.total || 0
      updateUnreadCount()
    }
  } catch (error) {
    console.error('加载通知失败:', error)
    ElMessage.error('加载通知失败')
  }
}

// 更新未读计数
const updateUnreadCount = () => {
  unreadCount.value = notifications.value.filter(n => !n.isRead).length
}

// 格式化时间 - 适配后端LocalDateTime格式
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  
  // 处理Java LocalDateTime格式 (e.g., "2023-05-14T10:30:00")
  const date = new Date(timeStr)
  
  // 格式化为 YYYY-MM-DD HH:mm
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 处理行点击
const handleRowClick = (notification) => {
  markAsRead(notification)
  
  // 根据通知类型跳转 - 使用后端字段名
  if (notification.relatedType === 'LOST' && notification.relatedLostItemId) {
    router.push(`/lost/detail/${notification.relatedLostItemId}`)
  } else if (notification.relatedType === 'FOUND' && notification.relatedFoundItemId) {
    router.push(`/found/detail/${notification.relatedFoundItemId}`)
  }
}

// 标记单个通知为已读 - 适配后端API
const markAsRead = async (notification) => {
  if (notification.isRead) return
  
  try {
    const token = localStorage.getItem('token')
    const response = await axios.put(`/notifications/${notification.id}/read`, {}, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    
    if (response.data && response.data.code === 200) {
      // 更新本地状态
      notification.isRead = true
      updateUnreadCount()
      ElMessage.success('标记已读成功')
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    console.error('标记通知已读失败:', error)
    ElMessage.error('标记已读失败')
  }
}

// 标记所有通知为已读 - 适配后端（逐个调用）
const markAllAsRead = async () => {
  try {
    const token = localStorage.getItem('token')
    const unreadIds = notifications.value
      .filter(n => !n.isRead)
      .map(n => n.id)
    
    if (unreadIds.length === 0) return
    
    // 逐个调用标记已读API
    const requests = unreadIds.map(id => 
      axios.put(`/notifications/${id}/read`, {}, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      })
    )
    
    await Promise.all(requests)
    
    // 更新本地状态
    notifications.value.forEach(n => {
      if (!n.isRead) n.isRead = true
    })
    unreadCount.value = 0
    ElMessage.success('全部标记为已读')
  } catch (error) {
    console.error('标记全部已读失败:', error)
    ElMessage.error('操作失败')
  }
}

onMounted(() => {
  loadNotifications()
})
</script>

<style scoped>
.notification-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.unread-indicator {
  width: 8px;
  height: 8px;
  background-color: #409eff;
  border-radius: 50%;
}

.notification-content {
  padding: 5px 0;
}

.notification-content.unread {
  font-weight: 500;
}

.related-item {
  margin-top: 6px;
  font-size: 12px;
  color: #666;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-table :deep(.cell) {
  padding: 8px 0;
}

.el-table :deep(.el-table__row) {
  cursor: pointer;
}

.el-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>